package com.gagakuai.domain.jude.expression;

import com.gagakuai.domain.facts.Facts;
import com.googlecode.aviator.AviatorEvaluatorInstance;
import com.googlecode.aviator.Expression;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @description: aviator表达式执行器
 * @author: houhong
 * @create: 2024-09-07 14:13
 **/
@Component
public class AviatorExpressExecutor {

    private static final Logger LOGGER = LoggerFactory.getLogger(AviatorExpressExecutor.class);

    final AviatorEvaluatorInstance aviator;

    public AviatorExpressExecutor(AviatorEvaluatorInstance aviator) {
        this.aviator = aviator;
    }

    public Object execute(String expression, Facts facts) {

        if (StringUtils.isBlank(expression)) {
            LOGGER.error("表达式不能为空");
            throw new RuntimeException();
        }

        try {
            aviator.validate(expression);
        } catch (Exception e) {
            //
            LOGGER.error("表达式不合法");
            throw new RuntimeException();
        }

        Expression compile = aviator.compile(expression, true);
        return compile.execute(facts.asMap());

    }
}
